﻿using System;
using System.IO;
using Microsoft.Win32;
using Newtonsoft.Json;

namespace AutoTask
{
	public class Tools : Singleton<Tools>
	{
		/// <summary>
		/// 保存设置
		/// </summary>
		/// <param name="fileName"></param>
		/// <param name="obj"></param>
		public void SaveJsonSetting(string fileName, object obj)
		{
			string json = JsonConvert.SerializeObject(obj);
			File.WriteAllText(fileName, json);
		}
		/// <summary>
		/// 获取
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="fileName"></param>
		/// <returns></returns>
		public T GetJsonSetting<T>(string fileName) where T:class,new()
		{
			string json = "";
			if (!File.Exists(fileName))
				File.CreateText(fileName);
			else
				json= File.ReadAllText(fileName);
			if (string.IsNullOrEmpty(json))
				return new T();
			else
				return JsonConvert.DeserializeObject<T>(json);
		}

		/// <summary>
		/// 设置应用程序开机自动运行
		/// </summary>
		/// <param name="fileName">应用程序的文件名</param>
		/// <param name="isAutoRun">是否自动运行，为false时，取消自动运行</param>
		/// <exception cref="System.Exception">设置不成功时抛出异常</exception>
		public void SetAutoRun(string fileName, bool isAutoRun)
		{
			RegistryKey reg = null;
			try
			{
				fileName = Path.GetFullPath(fileName);
				if (!System.IO.File.Exists(fileName))
					throw new Exception("该文件不存在!");
				String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
				reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
				if (reg == null)
					reg = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
				if (isAutoRun)
					reg.SetValue(name, fileName);
				else
					reg.SetValue(name, false);
			}
			catch (Exception ex)
			{
				throw new Exception(ex.ToString());
			}
			finally
			{
				if (reg != null)
					reg.Close();
			}

		}


		public void SendMail()
		{

		}

	}
}